package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDto;
import com.sky.dto.EmployeeLoginDto;
import com.sky.dto.EmployeeModifyPasswordDto;
import com.sky.dto.EmployeePageQueryDto;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.exception.extend.PasswordQuestionException;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.IEmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 管理端员的表现层开发
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录方案
     * @param employeeLoginDto
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVo> login(@RequestBody EmployeeLoginDto employeeLoginDto, HttpSession httpSession){
        EmployeeLoginVo employeeLoginVo = employeeService.findByUserName(employeeLoginDto);
        //存放id,并对session说拜拜
        //httpSession.setAttribute("employee",employeeLoginVo.getId());
        //使用Jwt技术来做登录验证
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID,employeeLoginVo.getId());//将员工的id写入载荷
       /* String jwtToken = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getAdminTokenName())//设置前端传来的名称
                .setExpiration(new Date(jwtProperties.getAdminTtl()))//设置过期时间
                .compact();*/
        String jwtToken = JwtUtil.createJWT(jwtProperties.getAdminSecretKey()
                ,jwtProperties.getAdminTtl(),
                claims);
        employeeLoginVo.setToken(jwtToken);
        return Result.success(employeeLoginVo);
    }

    /**
     * 员工退出
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(){
        return Result.success("退出成功");
    }

    /**
     * 注册新员工
     * @param employeeDto
     * @return
     */
    @PostMapping
    public Result<String> insert(@RequestBody EmployeeDto employeeDto){
        log.info("{}",employeeDto.toString());
        employeeService.insert(employeeDto);
        return Result.success("新增成功");
    }

    /**
     * 员工分页查询 表现层业务逻辑
     * @param employeePageQueryDto
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult<Employee>> page(EmployeePageQueryDto employeePageQueryDto){
        log.info("{}",employeePageQueryDto.toString());
        PageResult<Employee> result=employeeService.findByPage(employeePageQueryDto);
        return Result.success(result);
    }

    /**
     * 启用或者警用员工的状态
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> status(@PathVariable(value = "status") Integer status,
                                 Long id){
        log.info("status:{}",status);
        log.info("当前用户为id:{}",id);
        employeeService.modifyStatus(status,id);
        return Result.success("修改员工状态成功!");
    }
    @PutMapping("/editPassword")
    public Result<String> modifyPassword(@RequestBody EmployeeModifyPasswordDto employeeModifyPasswordDto){
        log.info("{}",employeeModifyPasswordDto.toString());
        //如果新密码与旧密码相同，那么抛出一个业务异常
        if (employeeModifyPasswordDto.getNewPassword().equals(employeeModifyPasswordDto.getOldPassword())){
            throw new PasswordQuestionException(MessageConstant.PASSWORD_THE_SAME);
        }
        //由于浏览器存在缓存的原有，防止其他用户的id登录，但是还是传给后台的数据是admin的id，会出现重大的经济损失
        if (!Objects.equals(employeeModifyPasswordDto.getEmpId(), BaseContext.getCurrentId())){
            throw new BusinessException("系统检测到你不是本用户,请重启系统重新登录");
        }
        //以下是正常的业务逻辑
        //1 在表现层将传来的密码进行md5加密,因为数据库是md5加密格式，方便结下了的业务逻辑
        employeeModifyPasswordDto.setNewPassword(DigestUtils.md5Hex(employeeModifyPasswordDto.getNewPassword()));
        employeeModifyPasswordDto.setOldPassword(DigestUtils.md5Hex(employeeModifyPasswordDto.getOldPassword()));
        employeeService.modifyPassword(employeeModifyPasswordDto);
        log.info("{}", employeeModifyPasswordDto);
        return Result.success("密码修改成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable(value = "id")Long id){
        return Result.success(employeeService.getById(id));
    }

    /**
     * 修改员工信息
     * @param employeeDto
     * @return
     */
    @PutMapping
    public Result<String> modifyEmployee(@RequestBody EmployeeDto employeeDto){
        //先进行封装
        Employee employee = Employee.builder()
                .id(employeeDto.getId())
                .sex(employeeDto.getSex())
                .idNumber(employeeDto.getIdNumber())
                .name(employeeDto.getName())
                .phone(employeeDto.getPhone())
                .username(employeeDto.getUsername())
                .build();
        log.info("employee-->{}",employee.toString());
        //传到业务层
        employeeService.modifyEmployee(employee);
        return Result.success("修改员工信息成功");
    }
}
